<template>
  <div>
    <van-field
      v-model="selectValue"
      is-link
      readonly
      label="课程"
      placeholder="请选择课程"
      @click="show = true"
    />
    <van-popup v-model="show" round position="buttom">
      <van-cascader
        title="请选择课程"
        :options="subjects"
        @close="show = false"
        @finish="onFinish"
      ></van-cascader>
    </van-popup>
    <van-search
      v-model="value"
      @search="onSearch"
      placeholder="请输入题目内容，支持模糊搜索"
    />
    <div class="learn_items">
      <van-row type="flex" justify="center">
        <learnItem
          :selectValue="selectedId"
          :imagePath="require('../../static/order.png')"
          @custom-event="handleEvent"
        ></learnItem>
        <learnItem
          :selectValue="selectedId"
          :imagePath="require('../../static/random.png')"
          learnItem="随机练习"
          @custom-event="handleEvent"
        ></learnItem>
      </van-row>
      <van-row type="flex" justify="center">
        <learnItem
          :selectValue="selectedId"
          :imagePath="require('../../static/wrong.png')"
          learnItem="错题练习"
          @custom-event="handleEvent"
        ></learnItem>
        <learnItem
          :selectValue="selectedId"
          :imagePath="require('../../static/collect.png')"
          learnItem="收藏练习"
          @custom-event="handleEvent"
        ></learnItem>
      </van-row>
      <van-row type="flex" justify="center">
        <learnItem
          :selectValue="selectedId"
          :imagePath="require('../../static/test.png')"
          learnItem="自我测试"
          @custom-event="handleEvent"
        ></learnItem>
        <learnItem
          :selectValue="selectedId"
          :imagePath="require('../../static/review.png')"
          learnItem="回顾试卷"
          ref="testItemRef"
          @custom-event="handleEvent"
        ></learnItem>
      </van-row>
    </div>
    <van-popup position="bottom" v-model="showPopUp">
      <div v-if="learnType == '自我测试'">
        <van-cell-group>
          <van-field
            v-model="testNum"
            label="试题数"
            placeholder="请输入试题数量"
            type="number"
          />
        </van-cell-group>
        <van-button
          style="margin-top: 5px"
          @click="confirm"
          type="info"
          size="small"
          >确 定</van-button
        >
      </div>
      <div v-if="learnType == '回顾试卷'">
        <van-icon name="arrow-left" size="40px" @click="showPopUp = false" />
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-swipe-cell v-for="item in list"
            ><van-cell
              :key="item.id"
              title="考试时间"
              :value="item.createTime"
              :label="`得分:${item.score}，用时：${item.usedTime}`"
              @click="reviewResult(`${item.selfTestId}`)"
            ></van-cell>
            <template #right>
              <van-button
                square
                type="danger"
                @click="deleteRusult(`${item.selfTestId}`)"
                text="删除"
              /> </template
          ></van-swipe-cell>
        </van-list>
      </div>
    </van-popup>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import subjectApi from "@/api/subject/index";
import learnItem from "@/views/learn/learnItem";
import lastRecord from "@/api/record/lastRecord";
import selfTestResult from "@/api/selfTest/selfTestResult";
import selfTest from "@/api/selfTest";
import { Dialog } from "vant";
import { Notify } from "vant";
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: { learnItem },
  props: {},
  data() {
    //这里存放数据
    return {
      currentPage: 0,
      pageSize: 5,
      list: [], //展示自测记录
      loading: false,
      finished: false,
      learnType: "", //随堂练习的类型
      selectValue: "",
      show: false,
      subjects: [],
      selectedId: -1,
      value: "",
      showPopUp: false,
      testNum: "", //考试题目的数量
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {
    selectedId() {
      this.currentPage = 0;
      this.list = [];
      this.finish = false;
      this.loading = false;
    },
  },
  //方法集合
  methods: {
    /**
     * 回顾考试记录
     * @param {self_test_result表的self_test_id} selfTestId
     */
    reviewResult(selfTestId) {
      this.$router.push({
        path: "/learn/learn",
        query: { selfTestId, type: "回顾错题" },
      });
    },
    /**
     * 删除用户的self_test记录
     * @param {self_test_result表的self_test_id} selfTestId
     */
    deleteRusult(selfTestId) {
      Dialog.confirm({
        message: "该试卷一旦删除将不可恢复！确定吗？",
      }).then(() => {
        selfTest.deleteById(selfTestId).then((res) => {
          Notify({ type: "success", message: `${res.data}` });
          //把该记录从列表中去除
          let filteredItems = [];
          for (let index = 0; index < this.list.length; index++) {
            const element = this.list[index];
            if (element.id != selfTestId) {
              filteredItems.push(element);
            }
          }
          this.list = filteredItems;
        });
      });
    },
    onLoad() {
      selfTestResult
        .getList(this.selectedId, this.currentPage, this.pageSize)
        .then((res) => {
          if (this.currentPage == 0 && res.data.length == 0) {
            Notify({ type: "danger", message: "没有记录！" });
            return;
          }
          if (res.data.length == 0) {
            this.finished = true;
            return;
          }
          for (let index = 0; index < res.data.length; index++) {
            const element = res.data[index];
            this.list.push(element);
          }
          //这里当点击下拉框时，第一页会出现两次，暂时没法解决，使用去重方法来解决
          if (this.currentPage <= 1) {
            let uniqueArray = Array.from(
              this.list
                .reduce((map, obj) => {
                  map.set(JSON.stringify(obj), obj);
                  return map;
                }, new Map())
                .values()
            );
            this.list = uniqueArray;
          }
          this.currentPage++;
          this.loading = false;
        });
    },
    confirm() {
      if (this.testNum == "" || this.testNum < 1) {
        Notify({ type: "danger", message: "题目数量不得为0或空！" });
        return;
      } else {
        this.$refs.testItemRef.seftTest(this.testNum);
        this.showPopUp = false;
        this.testNum = "";
      }
    },
    handleEvent(data) {
      if (data == "自我测试" || data == "回顾试卷") {
        this.learnType = data;
        this.showPopUp = true;
      }
    },
    onSearch() {
      /**
       * 当通过搜索题目进入刷题界面时，内部的功能和随机练习相同，不能记录做题记录，不能记录错题，index，但是可以记录错题，收藏等等
       */
      this.$router.push({
        path: "/learn/learn",
        query: { type: "随机练习", question: this.value },
      });
    },
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish({ selectedOptions }) {
      this.show = false;
      this.selectValue = selectedOptions.map((option) => option.text).join("/");
      this.selectedId = selectedOptions[1].value;
      //这里把用户此次选择的chapter保存到数据库中
      lastRecord.addOrUpdate(this.selectedId, this.selectValue);
      //把此次选择的chapter存放到缓存中
      const data = {
        selectValue: this.selectValue,
        selectedId: this.selectedId,
      };
      localStorage.setItem("selectChapter", JSON.stringify(data));
    },
    getSubject() {
      subjectApi.getTree().then((res) => {
        this.subjects = res.data;
        for (let index = 0; index < this.subjects.length; index++) {
          const element = this.subjects[index];
          //由于这里级联选择不能选择父组件，而为了让用户既能按照章节刷题，也能刷整个M3或者M2的题，因此在这里人为将级联选择子组件的值修改了以下
          //相比数据库中的数据，此处的子组件的数据多了一个父组件的值
          //而为了防止冲突，将人为加的一个值的value加10000，这里只要chapter表的值不超过10000，都不会冲突
          element.children.unshift({
            children: null,
            text: element.text,
            value: element.value + 10000,
          });
        }
      });
    },
    getLastRecord() {
      //先去缓存中查找用户上一次做的是哪个章节的练习题，如果缓存中没有再去数据库中查找
      let data = localStorage.getItem("selectChapter");
      if (data) {
        let params = JSON.parse(data);
        this.selectValue = params.selectValue;
        this.selectedId = params.selectedId;
      } else {
        lastRecord.getLastRecord().then((res) => {
          this.selectedId = res.data.selectedId;
          this.selectValue = res.data.chatperName;
          //把此次选择的chapter存放到缓存中
          const data = {
            selectValue: this.selectValue,
            selectedId: this.selectedId,
          };
          localStorage.setItem("selectChapter", JSON.stringify(data));
        });
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.getLastRecord();
    this.getSubject();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped>
.learn_items {
  margin-top: 20px;
}
</style>